// ...existing code...
document.addEventListener('DOMContentLoaded', () => {
    restoreSession();
    loadUsers();
    loadBooks();
    loadBorrowRecords();
    loadStats();

    document.getElementById('bookForm').addEventListener('submit', onBookFormSubmit);
    document.getElementById('registerForm').addEventListener('submit', onRegisterSubmit);
    document.getElementById('logoutBtn').addEventListener('click', logout);
    document.getElementById('impersonateBtn').addEventListener('click', impersonateSelectedUser);
    document.getElementById('borrowForm').addEventListener('submit', onBorrowSubmit);
    document.getElementById('searchBtn').addEventListener('click', searchBooks);
    document.getElementById('clearSearchBtn').addEventListener('click', () => { document.getElementById('searchQuery').value=''; loadBooks(); });
    document.getElementById('refreshStats').addEventListener('click', loadStats);
});

function currentUserKey() { return 'lm_current_user'; }

function saveSession(user) {
    localStorage.setItem(currentUserKey(), JSON.stringify(user));
    updateCurrentUserUI();
}

function restoreSession() {
    updateCurrentUserUI();
}

function logout() {
    localStorage.removeItem(currentUserKey());
    updateCurrentUserUI();
}

function updateCurrentUserUI() {
    const cur = localStorage.getItem(currentUserKey());
    const el = document.getElementById('currentUser');
    if (cur) {
        const u = JSON.parse(cur);
        el.textContent = `${u.name} (id:${u.id})`;
    } else {
        el.textContent = '未登录';
    }
}

async function onRegisterSubmit(e) {
    e.preventDefault();
    const name = document.getElementById('regName').value;
    const email = document.getElementById('regEmail').value;
    const password = document.getElementById('regPassword').value;
    try {
        const res = await fetch('/api/users/register', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({name, email, password})
        });
        if (!res.ok) {
            const err = await res.json();
            alert('注册失败: ' + (err.error || res.statusText));
            return;
        }
        const user = await res.json();
        saveSession(user);
        await loadUsers();
        alert('注册并登录成功');
        document.getElementById('registerForm').reset();
    } catch (err) {
        alert('网络错误');
    }
}

async function loadUsers() {
    const sel = document.getElementById('userSelect');
    const borrowSel = document.getElementById('borrowUser');
    sel.innerHTML = '';
    borrowSel.innerHTML = '';
    try {
        const res = await fetch('/api/users');
        const users = await res.json();
        users.forEach(u => {
            const opt = document.createElement('option');
            opt.value = u.id;
            opt.textContent = `${u.name} (${u.email})`;
            sel.appendChild(opt);

            const opt2 = opt.cloneNode(true);
            borrowSel.appendChild(opt2);
        });
    } catch (e) {
        console.warn('loadUsers error', e);
    }
}

function impersonateSelectedUser() {
    const sel = document.getElementById('userSelect');
    const id = sel.value;
    if (!id) return alert('请选择读者');
    // fetch user detail from list (simple approach: call ListUsers and find)
    fetch('/api/users?page=1&page_size=500')
        .then(r => r.json())
        .then(list => {
            const u = list.find(x => String(x.id) === String(id));
            if (u) {
                saveSession(u);
                alert('已切换为: ' + u.name);
            }
        });
}

async function onBookFormSubmit(e) {
    e.preventDefault();
    const id = document.getElementById('bookId').value;
    const book = {
        title: document.getElementById('title').value,
        author: document.getElementById('author').value,
        isbn: document.getElementById('isbn').value,
        publish_year: parseInt(document.getElementById('publishYear').value) || 0,
        available: document.getElementById('available').value === 'true'
    };
    try {
        if (id) {
            await fetch(`/api/books/${id}`, {
                method: 'PUT',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(book)
            });
        } else {
            await fetch('/api/books', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(book)
            });
        }
        document.getElementById('bookForm').reset();
        document.getElementById('bookId').value = '';
        await loadBooks();
        await loadBorrowBookOptions();
    } catch (e) {
        alert('保存失败');
    }
}

async function loadBooks() {
    try {
        const res = await fetch('/api/books');
        const books = await res.json();
        const bookList = document.getElementById('bookList');
        bookList.innerHTML = '';
        books.forEach(book => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>${escapeHtml(book.title)}</td>
                <td>${escapeHtml(book.author)}</td>
                <td>${escapeHtml(book.isbn)}</td>
                <td>${book.publish_year || ''}</td>
                <td>${book.available ? '是' : '否'}</td>
                <td>
                    <button data-action="edit" data-id="${book.id}">编辑</button>
                    <button data-action="delete" data-id="${book.id}">删除</button>
                </td>
            `;
            bookList.appendChild(tr);
        });
        // delegate events
        bookList.querySelectorAll('button[data-action="edit"]').forEach(btn => btn.addEventListener('click', onEditBook));
        bookList.querySelectorAll('button[data-action="delete"]').forEach(btn => btn.addEventListener('click', onDeleteBook));
        await loadBorrowBookOptions();
    } catch (e) {
        console.warn(e);
    }
}

function onEditBook(e) {
    const id = e.currentTarget.dataset.id;
    fetch(`/api/books/${id}`).then(r => r.json()).then(book => {
        document.getElementById('bookId').value = book.id;
        document.getElementById('title').value = book.title || '';
        document.getElementById('author').value = book.author || '';
        document.getElementById('isbn').value = book.isbn || '';
        document.getElementById('publishYear').value = book.publish_year || '';
        document.getElementById('available').value = book.available ? 'true' : 'false';
        window.scrollTo(0,0);
    });
}

async function onDeleteBook(e) {
    const id = e.currentTarget.dataset.id;
    if (!confirm('确认删除？')) return;
    await fetch(`/api/books/${id}`, { method: 'DELETE' });
    await loadBooks();
    await loadBorrowBookOptions();
}

async function searchBooks() {
    const q = document.getElementById('searchQuery').value.trim();
    if (!q) return loadBooks();
    const res = await fetch(`/api/books/search?q=${encodeURIComponent(q)}`);
    const books = await res.json();
    const bookList = document.getElementById('bookList');
    bookList.innerHTML = '';
    books.forEach(book => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${escapeHtml(book.title)}</td>
            <td>${escapeHtml(book.author)}</td>
            <td>${escapeHtml(book.isbn)}</td>
            <td>${book.publish_year || ''}</td>
            <td>${book.available ? '是' : '否'}</td>
            <td>
                <button data-action="edit" data-id="${book.id}">编辑</button>
                <button data-action="delete" data-id="${book.id}">删除</button>
            </td>
        `;
        bookList.appendChild(tr);
    });
    bookList.querySelectorAll('button[data-action="edit"]').forEach(btn => btn.addEventListener('click', onEditBook));
    bookList.querySelectorAll('button[data-action="delete"]').forEach(btn => btn.addEventListener('click', onDeleteBook));
}

async function loadBorrowBookOptions() {
    const sel = document.getElementById('borrowBook');
    sel.innerHTML = '';
    const res = await fetch('/api/books');
    const books = await res.json();
    books.forEach(b => {
        const opt = document.createElement('option');
        opt.value = b.id;
        opt.textContent = `${b.title} ${b.available ? '(可借)' : '(不可借)'}`;
        sel.appendChild(opt);
    });
}

async function onBorrowSubmit(e) {
    e.preventDefault();
    const userId = document.getElementById('borrowUser').value;
    const bookId = document.getElementById('borrowBook').value;
    const days = parseInt(document.getElementById('borrowDays').value) || 14;
    if (!userId || !bookId) return alert('请选择读者和图书');
    try {
        const res = await fetch('/api/borrow', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({user_id: Number(userId), book_id: Number(bookId), days})
        });
        if (!res.ok) {
            const err = await res.json();
            alert('借阅失败: ' + (err.error || res.statusText));
            return;
        }
        await loadBooks();
        await loadBorrowRecords();
        alert('借书成功');
    } catch (e) {
        alert('网络错误');
    }
}

async function loadBorrowRecords() {
    const tbody = document.getElementById('borrowList');
    tbody.innerHTML = '';
    try {
        const res = await fetch('/api/borrow_records');
        const records = await res.json();
        // need book title and user name - simple approach: fetch all books/users once
        const [booksRes, usersRes] = await Promise.all([fetch('/api/books'), fetch('/api/users?page=1&page_size=500')]);
        const books = await booksRes.json();
        const users = await usersRes.json();
        const bookMap = {};
        books.forEach(b => bookMap[b.id] = b);
        const userMap = {};
        users.forEach(u => userMap[u.id] = u);

        records.forEach(rec => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>${rec.id}</td>
                <td>${escapeHtml((bookMap[rec.book_id] && bookMap[rec.book_id].title) || '')}</td>
                <td>${escapeHtml((userMap[rec.user_id] && userMap[rec.user_id].name) || '')}</td>
                <td>${formatDate(rec.borrowed_at)}</td>
                <td>${formatDate(rec.due_at)}</td>
                <td>${rec.returned ? formatDate(rec.returned_at) : '否'}</td>
                <td>
                    ${rec.returned ? '' : `<button data-action="return" data-id="${rec.id}">归还</button>`}
                </td>
            `;
            tbody.appendChild(tr);
        });
        tbody.querySelectorAll('button[data-action="return"]').forEach(b => b.addEventListener('click', onReturnClick));
    } catch (e) {
        console.warn(e);
    }
}

async function onReturnClick(e) {
    const id = e.currentTarget.dataset.id;
    if (!confirm('确认归还？')) return;
    const res = await fetch(`/api/return/${id}`, { method: 'POST' });
    if (!res.ok) {
        const err = await res.json();
        alert('归还失败: ' + (err.error || res.statusText));
        return;
    }
    const data = await res.json();
    alert('已归还，罚款: ' + (data.fine || 0));
    await loadBooks();
    await loadBorrowRecords();
    await loadStats();
}

async function loadStats() {
    try {
        const res = await fetch('/api/stats/overview');
        const ov = await res.json();
        document.getElementById('overview').textContent = JSON.stringify(ov, null, 2);

        const tr = await fetch('/api/stats/top-borrowed?n=10');
        const top = await tr.json();
        const ol = document.getElementById('topBorrowed');
        ol.innerHTML = '';
        top.forEach(item => {
            const li = document.createElement('li');
            li.textContent = `${item.title} — ${item.count} 次`;
            ol.appendChild(li);
        });
    } catch (e) {
        console.warn('stats load error', e);
    }
}

// helper
function escapeHtml(s) {
    if (!s) return '';
    return String(s).replace(/[&<>"']/g, function(m){ return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]); });
}

function formatDate(v) {
    if (!v) return '';
    try {
        const d = new Date(v);
        if (isNaN(d)) return v;
        return d.toLocaleString();
    } catch (e) {
        return v;
    }
}